import {Component, Input, OnInit} from '@angular/core';
import {BaseComponent} from '@shared/base/base.component';
import {
  FormGroup,
  FormBuilder,
  Validators,
  FormControl,
  ValidationErrors
} from '@angular/forms';
import {Observable, of, Observer, Subject} from 'rxjs';
import {comparisonValue} from '@shared/utils/data.utils';
import {I18NService} from '@core/i18n/i18n.service';
import {NzFormatEmitEvent, NzMessageService} from 'ng-zorro-antd';
import {Knowledge} from "../../knowledge/model/knowledge";
import {KnowledgeService} from "../../knowledge/services/knowledge.service";


@Component({
  selector: 'knowledge-modify',
  templateUrl: './knowledge-modify.html'
})

export class KnowledgeModifyComponent extends BaseComponent implements OnInit {
  _id: number;

  @Input()
  set id(val: number) {
    this._id = val;
  }

  validateForm: FormGroup;

  searchOptions = [];

  tempItem: Knowledge;

  isCheck = true;
  value: number;
  page = {
    pageNo: 1,
    pageSize: 999
  };

  constructor(
    private fb: FormBuilder,
    private knowledgeService: KnowledgeService,
    private message: NzMessageService,
    private i18nService: I18NService
  ) {
    super();
    this.validateForm = this.fb.group({
      knowledgeName: [null, [Validators.required]],
      dept: null,
      pid: 0,
      gmtModified: null
    });
  }

  ngOnInit(): void {
    if (this._id !== undefined) {
      this.getKnowledge(this._id);
    }
    this.getKnowledgeByPid(0);
  }


  onExpandChange(e: NzFormatEmitEvent): void {
    console.log(e);
    if (e.node.getChildren().length === 0 && e.node.isExpanded) {
      this.knowledgeService.getKnowledgeByPid(parseInt(e.node.origin.key, 0))
        .subscribe(res => {
          e.node.addChildren(res);
        });
      this.value = e.node.origin.key;
    }
  }

  submit(): Observable<any> {
    return new Observable((sub) => {
      if (!this.valid()) {
        sub.error(null);
        return;
      }
      if (this.isCheck) {
        this.isCheck = false;
        if (this._id !== undefined) {
          const saveVal: Knowledge = {
            id: this._id,
            ...comparisonValue(this.validateForm.value, this.tempItem)
          };
          this.update(saveVal).subscribe(res => {
            sub.next();
          }, err => {
            sub.error();
          });
        } else {
          this.add(this.validateForm.value).subscribe(res => {
            sub.next();
          }, err => {
            sub.error();
          });
        }
      }
    });
  }

  cancel(): Observable<any> {
    return of('cancel');
  }

  getKnowledgeByPid(pid: number): void {
    this.knowledgeService.getKnowledgeByPid(pid)
      .subscribe(res => {
        this.searchOptions = res;
      });
  }

  getKnowledgeParentByPage(): void {
    this.knowledgeService.getKnowledgeParentByPage(1, 500)
      .subscribe(res => {
        this.searchOptions = res.records;
      });
  }

  getKnowledge(id: number): void {
    this.knowledgeService.getKnowledgeById(id)
      .subscribe(res => {
        this.tempItem = res;
        this.validateForm.patchValue(res);
        if (res.pid !== -1) {
          // this.searchChange('', res.pid);
        }
      });
  }

  searchChange(val?: string): void {
    this.knowledgeService.getKnowledgeByName(this.page.pageNo, this.page.pageSize, val)
      .subscribe(res => {
        this.searchOptions = res.records;
      });
  }

  add(item: Knowledge): Observable<void> {
    return new Observable((sub) => {
      this.knowledgeService.addKnowledge(item)
        .subscribe(res => {
          this.message.success(this.i18nService.translate('modify.return.add_success'));
          this.isCheck = true;
          sub.next();
        }, err => {
          this.isCheck = true;
          sub.error();
        });
    });
  }

  update(item: Knowledge): Observable<void> {
    return new Observable((sub) => {
      this.knowledgeService.updateKnowledge(item)
        .subscribe(res => {
          if (res) {
            this.message.success(this.i18nService.translate('modify.return.edit_success'));
          } else {
            this.message.error(this.i18nService.translate('modify.return.eidt_error'));
          }
          this.isCheck = true;
          sub.next();
        }, err => {
          this.isCheck = true;
          sub.error();
        });
    });
  }
}
